/**
 * 图像处理工具类
 */

/**
 * 裁剪图片
 */
export function cropImage(
  imageDataUrl: string,
  x: number,
  y: number,
  width: number,
  height: number
): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext('2d')
      
      if (!ctx) {
        reject(new Error('无法获取 Canvas 上下文'))
        return
      }

      ctx.drawImage(img, x, y, width, height, 0, 0, width, height)
      resolve(canvas.toDataURL('image/png'))
    }
    img.onerror = reject
    img.src = imageDataUrl
  })
}

/**
 * 应用马赛克效果
 */
export function applyMosaic(
  imageData: ImageData,
  mosaicSize: number = 10
): ImageData {
  const { data, width, height } = imageData
  const result = new ImageData(width, height)

  for (let y = 0; y < height; y += mosaicSize) {
    for (let x = 0; x < width; x += mosaicSize) {
      // 计算块的平均颜色
      let r = 0, g = 0, b = 0, a = 0, count = 0

      for (let dy = 0; dy < mosaicSize && y + dy < height; dy++) {
        for (let dx = 0; dx < mosaicSize && x + dx < width; dx++) {
          const index = ((y + dy) * width + (x + dx)) * 4
          r += data[index]
          g += data[index + 1]
          b += data[index + 2]
          a += data[index + 3]
          count++
        }
      }

      r = Math.floor(r / count)
      g = Math.floor(g / count)
      b = Math.floor(b / count)
      a = Math.floor(a / count)

      // 填充块
      for (let dy = 0; dy < mosaicSize && y + dy < height; dy++) {
        for (let dx = 0; dx < mosaicSize && x + dx < width; dx++) {
          const index = ((y + dy) * width + (x + dx)) * 4
          result.data[index] = r
          result.data[index + 1] = g
          result.data[index + 2] = b
          result.data[index + 3] = a
        }
      }
    }
  }

  return result
}

/**
 * 调整图片大小
 */
export function resizeImage(
  imageDataUrl: string,
  maxWidth: number,
  maxHeight: number
): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      let width = img.width
      let height = img.height

      // 计算缩放比例
      if (width > maxWidth || height > maxHeight) {
        const ratio = Math.min(maxWidth / width, maxHeight / height)
        width *= ratio
        height *= ratio
      }

      const canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext('2d')

      if (!ctx) {
        reject(new Error('无法获取 Canvas 上下文'))
        return
      }

      ctx.drawImage(img, 0, 0, width, height)
      resolve(canvas.toDataURL('image/png'))
    }
    img.onerror = reject
    img.src = imageDataUrl
  })
}

/**
 * 生成缩略图
 */
export function generateThumbnail(
  imageDataUrl: string,
  thumbnailWidth: number = 200
): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const ratio = thumbnailWidth / img.width
      const thumbnailHeight = img.height * ratio

      const canvas = document.createElement('canvas')
      canvas.width = thumbnailWidth
      canvas.height = thumbnailHeight
      const ctx = canvas.getContext('2d')

      if (!ctx) {
        reject(new Error('无法获取 Canvas 上下文'))
        return
      }

      ctx.drawImage(img, 0, 0, thumbnailWidth, thumbnailHeight)
      resolve(canvas.toDataURL('image/jpeg', 0.7))
    }
    img.onerror = reject
    img.src = imageDataUrl
  })
}

/**
 * 转换图片格式
 */
export function convertImageFormat(
  imageDataUrl: string,
  format: 'image/png' | 'image/jpeg' | 'image/webp',
  quality: number = 1.0
): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')

      if (!ctx) {
        reject(new Error('无法获取 Canvas 上下文'))
        return
      }

      ctx.drawImage(img, 0, 0)
      resolve(canvas.toDataURL(format, quality))
    }
    img.onerror = reject
    img.src = imageDataUrl
  })
}

/**
 * 下载图片
 */
export function downloadImage(dataUrl: string, filename: string) {
  const link = document.createElement('a')
  link.href = dataUrl
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 生成文件名
 */
export function generateFilename(prefix: string = 'Screenshot', extension: string = 'png'): string {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `${prefix}_${year}${month}${day}_${hours}${minutes}${seconds}.${extension}`
}

